package pl.pasu.ocrtc;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.os.AsyncTask;

public class RemoteOcrEngine extends OcrEngine {

    private static String TAG = "RemoteOcrEngine";
    private static String[] URL_STRINGS = {"http://proton.techcasita.com:8080"};
    private byte[] mBA;
    private OcrDoneCallback mCallback;

    @Override
    public void readImage(Bitmap bmp, OcrDoneCallback callback) {
        mCallback = callback;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        mBA = stream.toByteArray();
        new OCRTask().execute(URL_STRINGS);
    }
    private class OCRTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(final String... urls) {
            String response = "";
            for (String url : urls) {
                try {
                    response = executeMultipartPost(url, mBA);
                    Logger.v(TAG, "Response:" + response);
                    break;
                } catch (Throwable ex) {
                    Logger.e(TAG, "error: " + ex.getMessage());
                }
            }
            return response;
        }

        @Override
        protected void onPostExecute(final String result) {
            mCallback.onOcrDone(result);
        }
    }

    private String executeMultipartPost(final String stringUrl, final byte[] bm) throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(stringUrl);
        ByteArrayBody bab = new ByteArrayBody(bm, "the_image.jpg");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("uploaded", bab);
        reqEntity.addPart("name", new StringBody("the_file"));
        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse).append('\n');
        }
        int i = s.indexOf("body");
        int j = s.lastIndexOf("body");
        return s.substring(i + 5, j - 2);
    }
}
